package com.ys168.gam.shortestpath.message;

import java.beans.Beans;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import com.ys168.gam.shortestpath.util.FileUtil;

public class Messages {

    private static final String BUNDLE_NAME = "config.messages"; //$NON-NLS-1$
    
    private static final String CHARSET = "UTF-8";
    private static final String DEFAULT = "zh_CN";
    private static final String LANGUAGE_PATH = "/config/language.ini";
    private static final String INFORMATE_PATH = "/config/information/information_%s.html";

    private static String language = loadDefaultLanguage();
    private static ResourceBundle RESOURCE_BUNDLE = loadBundle(language);
    
    public static URL getInformationUrl() {
        return Messages.class.getResource(String.format(INFORMATE_PATH, language));
    }
    
    public static String getLanguage() {
        return language;
    }

    public static String getString(String key) {
        try {
            ResourceBundle bundle = Beans.isDesignTime() ? loadBundle(DEFAULT) : RESOURCE_BUNDLE;
            return new String(bundle.getString(key).getBytes("ISO-8859-1"), CHARSET);
        }
        catch (MissingResourceException e) {
            return "!" + key + "!";
        }
        catch (UnsupportedEncodingException e) {
            return "!" + key + "!";
        }
    }
    
    private static ResourceBundle loadBundle(String language) {
        Messages.language = language;
        
        String bundleName = DEFAULT.equals(language) ? BUNDLE_NAME : "config.messages_" + language;
        RESOURCE_BUNDLE = ResourceBundle.getBundle(bundleName);
        return RESOURCE_BUNDLE;
    }

    private static String loadDefaultLanguage() {
        InputStream input = Messages.class.getResourceAsStream(LANGUAGE_PATH);
        String string = FileUtil.loadFrom(input);
        return string == null ? DEFAULT : string;
    }
    
    private Messages() {}
    
    public static void main(String[] args) {
        System.out.println(Messages.class.getResource("/config/language.ini"));
    }
}
